package com.example.hezhe_backend.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@EnableWebSecurity
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/login.html","/register.html","/error.html").permitAll()
                .antMatchers("/css/**").permitAll()
                .antMatchers("/img/**").permitAll()
                .antMatchers("/libs/**").permitAll()
//                .antMatchers("/fonts/**").permitAll()
//                .antMatchers("/plugins/**").permitAll()
                .antMatchers("/pages/**").authenticated()
                .antMatchers("/admin.html").hasAuthority("ADMIN")
                .and()
                .formLogin()
                .loginPage("/login.html")
                .usernameParameter("username")
                .passwordParameter("password")
                .loginProcessingUrl("/login")
                .defaultSuccessUrl("/pages/index.html")
                .failureUrl("/login.html")
                .and()
                .logout()
                .and()
                .csrf().disable()
                .headers().frameOptions().disable();
    }

//    @Override
//    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        auth.inMemoryAuthentication()
//                .withUser("xukai")
//                .password(new BCryptPasswordEncoder().encode("123456qwer"))
//                .roles("ADMIN");
//        auth.inMemoryAuthentication()
//                .withUser("libo")
//                .password(new BCryptPasswordEncoder().encode("123"))
//                .roles("USER");
//    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

}
